package com.weixin.servlet.impl;

import com.weixin.bean.MessageBean;
import com.weixin.bean.SendMessageBean;
import com.weixin.bean.SendMsgDto;
import com.weixin.dao.IMessageDao;
import com.weixin.dao.ISendMessageDao;
import com.weixin.servlet.ISendMessageKeyServlet;
import com.weixin.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018-01-24.
 */
@Service
@Transactional
public class SendMessageKeyServlet implements ISendMessageKeyServlet {
    @Autowired
    private ISendMessageDao sendMessageDao ;

    @Autowired
    private IMessageDao messageDao ;
    /**
     *
     * 根据关键词回复消息
     *
     * @param bean
     * @return
     */
    @Override
    public String sendMessage(MessageBean bean) {

        String  str = null ;
        List<SendMessageBean> keyList = sendMessageDao.getAllKey();
        for(SendMessageBean key : keyList) {
            if (bean.getContent().equals(key.getKeyStr())) {
                MessageBean message = new MessageBean();

                message.setFromUserName(bean.getToUserName());//原来【接收消息用户】变为回复时【发送消息用户】

                message.setToUserName(bean.getFromUserName());

                message.setMsgType(key.getToMessageType());

                message.setCreateTime(new Date().getTime() + "");//创建当前时间为消息时间

                message.setContent(key.getContent());

                str = MessageUtils.objectToXml(message); //调用Message工具类，将对象转为XML字符串
                key.setCount(key.getCount()+1);
                sendMessageDao.addCount(key);
                SendMsgDto dto = new SendMsgDto();
                dto.setId(key.getId());
                dto.setMessageId(bean.getId());
                dto.setCreateTime(new Date().getTime());
                //TODO   操作员姓名
                dto.setUserName("操作员姓名");
                sendMessageDao.InsertSendDetail(dto);
                messageDao.updateReply(bean);
                break;
            }
        }
        return str;
    }
}
